﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Threading.Tasks;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.Helper;

namespace YiYiTong.Rocket.Business
{
    public class SmsBiz
    {
        #region 单例模式
        private SmsBiz()
        {
        }

        private static SmsBiz _instance;
        private static readonly object _syncObject = new object();

        public static SmsBiz Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new SmsBiz();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion 单例模式

        /// <summary>
        /// 发送手机短信,根据内容进行发送
        /// </summary>
        /// <returns></returns>
        public bool SendMessage(string mobile, string message)
        {
            if (ConfigHelper.AppSetting<bool>("IsReqThird"))
                return ChLanApiBiz.SendMessage(mobile, message);
            else
                return true;
        }
        /// <summary>
        /// 发送手机短信
        /// sendType 1 登录短信 2 绑定账户 3 设置支付密码
        /// </summary>
        /// <returns></returns>
        public bool SendMessage(string mobile, int sendType)
        {
            //获取短信内容
            string message = GetMessage(sendType);
            if (string.IsNullOrEmpty(message))
            {
                LogHelper.Error("发送手机短信失败：短信内容获取失败");
                return false;
            }
            string code = code = Utils.GetRandom();
            string environment = ConfigHelper.AppSetting<string>("environment");
            if (environment == "dev" || mobile.Equals("13816323257"))
                code = "666666";

            if (EnumHelper.IsDefined<SendType>(sendType))
                message = string.Format(message, code);
            else
                return false;

            //验证码保存缓存redis中
            if (!SaveCode(mobile, sendType, code))
            {
                LogHelper.Error("发送手机短信失败：验证码保存失败");
                return false;
            }
            if (ConfigHelper.AppSetting<bool>("IsReqThird") && !mobile.Equals("13816323257"))
                return ChLanApiBiz.SendMessage(mobile, message);
            else
                return true;
        }

        /// <summary>
        /// 验证码保存缓存redis中
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="sendType"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private bool SaveCode(string mobile, int sendType, string code)
        {
            string codeKey = string.Format("code-{0}-{1}", mobile, sendType);
            string mobileKey = string.Format("mobile-{0}-{1}", mobile, sendType);

            //用于防止60秒内用户重复请求发送短信
            string strMobile = RedisService.Get<string>(mobileKey);
            if (!string.IsNullOrEmpty(strMobile))
            {
                if (strMobile != mobile)
                    RedisService.Set(mobileKey, mobile, DateTime.Now.AddMinutes(1));
                else
                    return false;
            }
            else
                RedisService.Set(mobileKey, mobile, DateTime.Now.AddMinutes(1));

            //生成新的验证码前，移除旧的验证码（5分钟过期验证码） 
            if (!string.IsNullOrEmpty(RedisService.Get<string>(codeKey)))
            {
                RedisService.Remove(codeKey);
            }
            //验证码保存缓存redis中
            int smsCodevValid = ConfigHelper.AppSetting<int>("smsCodevValid", 5); //验证码有效期改为配置文件中配置
            if (RedisService.Set(codeKey, code, DateTime.Now.AddMinutes(smsCodevValid)))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 通过发送类型获取配置中的短信内容
        /// </summary>
        /// <param name="sendType"></param>
        /// <returns></returns>
        private string GetMessage(int sendType)
        {
            string message = string.Empty;
            string jsonFile = System.Web.HttpContext.Current.Server.MapPath("~/Config/SmsMessage.json");
            List<SmsContext> list = JsonHelper.DeserializeFileList<SmsContext>(jsonFile);
            if (list != null && list.Count != 0)
            {
                var context = list.FirstOrDefault(s => s.sendtype == sendType);
                if (context != null)
                {
                    message = context.message;
                }
            }

            return message;
        }
    }
}
